package org.abettor.pushbox.view;

import org.abettor.pushbox.map.Boxmap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

/**
 * 画缩略图的操作
 * 
 * @author jzh
 * 
 */
public class BoxMapThumbnailDraw {
	private float width, height;// 图片的宽度和高度
	private BoxMapImageDraw imageDraw;// 图片绘制的类
	private Boxmap map;// 地图
	protected Matrix mBaseMatrix = new Matrix();// 基准图片的matrix

	/**
	 * 构造函数
	 * 
	 * @param context
	 */
	public BoxMapThumbnailDraw(Context context) {
		imageDraw = new BoxMapImageDraw(context);
	}

	/**
	 * 绘制缩略图的操作
	 * 
	 * @return
	 */
	public Bitmap draw() {
		Bitmap bitmap = createBitmap();
		drawBitmap(bitmap);
		setBaseMatrix(bitmap, mBaseMatrix);
		Bitmap ret = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), mBaseMatrix, true);
		return ret;
	}

	/**
	 * 绘制草稿的缩略图
	 * 
	 * @return
	 */
	public Bitmap drawDraftImage() {
		Bitmap bitmap = createBitmap();
		drawGrid(bitmap);
		setBaseMatrix(bitmap, mBaseMatrix);
		Bitmap ret = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), mBaseMatrix, true);
		return ret;
	}

	// 绘制坐标系
	private void drawGrid(Bitmap bitmap) {
		Canvas c1 = new Canvas(bitmap);
		Paint paint = new Paint();
		for (int y = 0; y < map.getHeight(); y++) {
			for (int x = 0; x < map.getWidth(); x++) {
				if (map.isEmpty(x, y)) {
					imageDraw.drawBackGroudClip(c1, x, y, paint);
				} else {
					imageDraw.drawEveryClipWithOutBack(c1, x, y, map);
				}
			}
		}
	}

	private void setBaseMatrix(Bitmap bitmap, Matrix matrix) {
		matrix.reset();
		float widthScale = Math.min(width / (float) bitmap.getWidth(), 1.0f);
		float heightScale = Math.min(height / (float) bitmap.getHeight(), 1.0f);
		float scale;
		if (widthScale > heightScale) {
			scale = heightScale;
		} else {
			scale = widthScale;
		}
		matrix.setScale(scale, scale);
		matrix.postTranslate(
				(width - ((float) bitmap.getWidth() * scale)) / 2F,
				(height - ((float) bitmap.getHeight() * scale)) / 2F);
	}

	// 开始绘图的操作
	private void drawBitmap(Bitmap bitmap) {
		Canvas c1 = new Canvas(bitmap);
		for (int y = 0; y < map.getHeight(); y++) {
			for (int x = 0; x < map.getWidth(); x++) {
				imageDraw.drawEveryClip(c1, x, y, map);
			}
		}
	}

	// 创建背景图片
	private Bitmap createBitmap() {
		float width = imageDraw.getClipWidth() * map.getWidth();
		float height = imageDraw.getClipHeight() * map.getHeight();
		Bitmap mPushBoxImage = Bitmap.createBitmap((int) width, (int) height,
				Bitmap.Config.RGB_565);
		return mPushBoxImage;
	}

	public void setWidth(float width) {
		this.width = width;
	}

	public void setHeight(float height) {
		this.height = height;
	}

	public void setMap(Boxmap map) {
		this.map = map;
	}

}
